package com.songshuai.webapi.jobapi.common.sysimpl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

@Component
public class RedisStringSerializer  implements RedisSerializer<String> {
    private final Charset charset;

    @Value("${spring.redis.key-prefix}")
    private String cachePrefix;

    public RedisStringSerializer(){
        this ( Charset.forName ( "UTF8" ) );
    }
    public RedisStringSerializer(Charset charset ){
        this.charset = charset;
    }

    @Override
    public byte[] serialize(String s) throws SerializationException {
        String keyPrefix = cachePrefix;
        String key = keyPrefix + s;
        return (key == null ? null : key.getBytes ( charset ));
    }

    @Override
    public String deserialize(byte[] bytes) throws SerializationException {
        String keyPrefix = cachePrefix;
        String saveKey = new String ( bytes, charset );
        int indexOf = saveKey.indexOf ( keyPrefix );
        if (indexOf > 0) {

        } else {
            saveKey = saveKey.substring ( indexOf );
        }
        return (saveKey.getBytes () == null ? null : saveKey);
    }
}
